package com.hzw.saas.service.old.hub.util;

import java.io.InputStream;
import java.io.OutputStream;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 文件数据流读写器
 * @author yuli
 *
 */
public class FileStreams {

	static Log log = LogFactory.get();

	/**
	 * 定长转发
	 * @param ins
	 * @param ous
	 * @param length
	 * @param BUF_SIZE
	 * @throws Exception
	 */
	public static void readAndWrite(InputStream ins, OutputStream ous, long length, int BUF_SIZE, boolean closeOus) throws Exception {
		byte[] buff = new byte[BUF_SIZE];

		int remain = (int) length;
		int avalible = BUF_SIZE;

		try {
			for (; remain > 0;) {
				if(log.isTraceEnabled()) {
					log.trace("remain:" + remain);
				}

				if (remain < BUF_SIZE) {
					avalible = remain;
				}
				if(log.isTraceEnabled()) {
					log.trace("avalible:" + avalible);
				}

				int len = ins.read(buff, 0, avalible);
				if(log.isTraceEnabled()) {
					log.trace("readlen:" + len);
				}

				if(len < 0) {
					log.warn("read len < 0, filedata is missing");
					break;
				}

				ous.write(buff, 0, len);
				ous.flush();
				remain -= len;
			}

		} catch (Exception e) {
			log.error("receive file data error", e);
			throw e;
		}
		finally {
			if (null != ous && closeOus) {
				ous.close();
			}
		}
	}

	/**
	 * 未知长度转发（读取到-1为止）
	 * @param ins
	 * @param ous
	 * @param BUF_SIZE
	 */
	public static long readAndWrite(InputStream ins, OutputStream ous, int BUF_SIZE, boolean closeOus) throws Exception {
		long length = 0;
		byte[] buf = new byte[BUF_SIZE];
		int size = 0;
		try {
			while((size = ins.read(buf)) != -1){
				ous.write(buf, 0, size);
				length += size;
			}
		}
		finally {
			if (null != ous && closeOus) {
				ous.close();
			}
		}
		return length;
	}

}
